package com.resource.error;

import com.alibaba.fastjson.JSON;
import com.utility.constant.HttpConstant;
import com.utility.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限不足处理类 返回403
 * @author: hw
 * @date: 2020/12/10 16:06
 */
@Component
@Slf4j
public class AuthenticationAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * 处理访问拒绝失败。
     * @param request
     * @param response
     * @param accessDeniedException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        String msg =  "请求: "+ request . getRequestURI ()+ ( " 权限不足，无法访问系统资源.");
        //设置缓存区编码为UTF-8编码格式
        response.setCharacterEncoding(HttpConstant.UTF8);
        //在响应中主动告诉浏览器使用UTF-8编码格式来接收数据
        response.setHeader(HttpConstant.CONTENT_TYPE, HttpConstant.REQUEST_HOST_JSON);
        log.info(accessDeniedException.getMessage());
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(JSON.toJSONString(Result.returnCode(401,msg)));

    }
}
